using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace Lzfy_Refund_Service.Controllers
{
    /// <summary>
    /// 银行信息管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class BankInfoController : ControllerBase
    {
        private readonly IBankInfoService _bankInfoService;
        private readonly ILogger<BankInfoController> _logger;

        public BankInfoController(IBankInfoService bankInfoService, ILogger<BankInfoController> logger)
        {
            _bankInfoService = bankInfoService;
            _logger = logger;
        }

        /// <summary>
        /// 获取银行信息列表（分页）
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<PagedResponse<BankInfoResponse>>> GetBankInfoList([FromQuery] BankInfoQueryRequest request)
        {
            try
            {
                var result = await _bankInfoService.GetBankInfoListAsync(request);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取银行信息列表失败");
                return StatusCode(500, new { message = "获取银行信息列表失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取银行信息详情
        /// </summary>
        /// <param name="id">银行ID</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<BankInfoResponse>> GetBankInfoById([Required] int id)
        {
            try
            {
                var result = await _bankInfoService.GetBankInfoByIdAsync(id);
                if (result == null)
                {
                    return NotFound(new { message = "银行信息不存在" });
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取银行信息详情失败，ID: {BankId}", id);
                return StatusCode(500, new { message = "获取银行信息详情失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 创建银行信息
        /// </summary>
        /// <param name="request">创建请求</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> CreateBankInfo([FromBody] BankInfoCreateRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var createdBy = GetCurrentUser();
                var result = await _bankInfoService.CreateBankInfoAsync(request, createdBy);

                if (result.success)
                {
                    return CreatedAtAction(nameof(GetBankInfoById), new { id = result.bankId }, 
                        new { message = result.message, bankId = result.bankId });
                }
                else
                {
                    return BadRequest(new { message = result.message });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建银行信息失败");
                return StatusCode(500, new { message = "创建银行信息失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 更新银行信息
        /// </summary>
        /// <param name="id">银行ID</param>
        /// <param name="request">更新请求</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ActionResult> UpdateBankInfo([Required] int id, [FromBody] BankInfoUpdateRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var updatedBy = GetCurrentUser();
                var result = await _bankInfoService.UpdateBankInfoAsync(id, request, updatedBy);

                if (result.success)
                {
                    return Ok(new { message = result.message });
                }
                else
                {
                    return BadRequest(new { message = result.message });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新银行信息失败，ID: {BankId}", id);
                return StatusCode(500, new { message = "更新银行信息失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 删除银行信息
        /// </summary>
        /// <param name="id">银行ID</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteBankInfo([Required] int id)
        {
            try
            {
                var deletedBy = GetCurrentUser();
                var result = await _bankInfoService.DeleteBankInfoAsync(id, deletedBy);

                if (result.success)
                {
                    return Ok(new { message = result.message });
                }
                else
                {
                    return BadRequest(new { message = result.message });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除银行信息失败，ID: {BankId}", id);
                return StatusCode(500, new { message = "删除银行信息失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 搜索银行信息
        /// </summary>
        /// <param name="keyword">搜索关键词</param>
        /// <param name="limit">限制数量</param>
        /// <returns></returns>
        [HttpGet("search")]
        public async Task<ActionResult<List<BankSearchResponse>>> SearchBankInfo(
            [Required] string keyword, 
            [Range(1, 50)] int limit = 10)
        {
            try
            {
                var result = await _bankInfoService.SearchBankInfoAsync(keyword, limit);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索银行信息失败，关键词: {Keyword}", keyword);
                return StatusCode(500, new { message = "搜索银行信息失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 验证银行卡信息
        /// </summary>
        /// <param name="request">验证请求</param>
        /// <returns></returns>
        [HttpPost("validate")]
        public async Task<ActionResult<BankCardValidationResponse>> ValidateBankCard([FromBody] BankCardValidationRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _bankInfoService.ValidateBankCardAsync(request);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证银行卡信息失败");
                return StatusCode(500, new { message = "验证银行卡信息失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取所有启用的银行列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("active")]
        public async Task<ActionResult<List<BankSearchResponse>>> GetAllActiveBanks()
        {
            try
            {
                var result = await _bankInfoService.GetAllActiveBanksAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有启用银行列表失败");
                return StatusCode(500, new { message = "获取所有启用银行列表失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 更新银行BIN码映射
        /// </summary>
        /// <param name="id">银行ID</param>
        /// <param name="binCodes">BIN码列表</param>
        /// <returns></returns>
        [HttpPut("{id}/bin-codes")]
        public async Task<ActionResult> UpdateBankBinMappings([Required] int id, [FromBody] List<string> binCodes)
        {
            try
            {
                var updatedBy = GetCurrentUser();
                var result = await _bankInfoService.UpdateBankBinMappingsAsync(id, binCodes, updatedBy);

                if (result.success)
                {
                    return Ok(new { message = result.message });
                }
                else
                {
                    return BadRequest(new { message = result.message });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新银行BIN码映射失败，银行ID: {BankId}", id);
                return StatusCode(500, new { message = "更新银行BIN码映射失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 更新银行别名
        /// </summary>
        /// <param name="id">银行ID</param>
        /// <param name="aliases">别名列表</param>
        /// <returns></returns>
        [HttpPut("{id}/aliases")]
        public async Task<ActionResult> UpdateBankAliases([Required] int id, [FromBody] List<BankAliasRequest> aliases)
        {
            try
            {
                var updatedBy = GetCurrentUser();
                var result = await _bankInfoService.UpdateBankAliasesAsync(id, aliases, updatedBy);

                if (result.success)
                {
                    return Ok(new { message = result.message });
                }
                else
                {
                    return BadRequest(new { message = result.message });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新银行别名失败，银行ID: {BankId}", id);
                return StatusCode(500, new { message = "更新银行别名失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取银行变更日志
        /// </summary>
        /// <param name="bankId">银行ID（可选）</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <returns></returns>
        [HttpGet("change-logs")]
        public async Task<ActionResult<PagedResponse<BankInfoChangeLog>>> GetChangeLogs(
            int? bankId = null, 
            [Range(1, int.MaxValue)] int pageIndex = 1, 
            [Range(1, 100)] int pageSize = 20)
        {
            try
            {
                var result = await _bankInfoService.GetChangeLogsAsync(bankId, pageIndex, pageSize);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取银行变更日志失败");
                return StatusCode(500, new { message = "获取银行变更日志失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 导出银行信息数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("export")]
        public async Task<ActionResult<List<BankInfoResponse>>> ExportBankInfo()
        {
            try
            {
                var result = await _bankInfoService.ExportBankInfoAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出银行信息数据失败");
                return StatusCode(500, new { message = "导出银行信息数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 导入银行信息数据
        /// </summary>
        /// <param name="bankInfoList">银行信息列表</param>
        /// <returns></returns>
        [HttpPost("import")]
        public async Task<ActionResult> ImportBankInfo([FromBody] List<BankInfoCreateRequest> bankInfoList)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var importedBy = GetCurrentUser();
                var result = await _bankInfoService.ImportBankInfoAsync(bankInfoList, importedBy);

                if (result.success)
                {
                    return Ok(new 
                    { 
                        message = result.message, 
                        successCount = result.successCount, 
                        failCount = result.failCount 
                    });
                }
                else
                {
                    return BadRequest(new 
                    { 
                        message = result.message, 
                        successCount = result.successCount, 
                        failCount = result.failCount 
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导入银行信息数据失败");
                return StatusCode(500, new { message = "导入银行信息数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 批量操作银行信息状态
        /// </summary>
        /// <param name="request">批量操作请求</param>
        /// <returns></returns>
        [HttpPost("batch-status")]
        public async Task<ActionResult> BatchUpdateStatus([FromBody] BatchStatusUpdateRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var updatedBy = GetCurrentUser();
                var successCount = 0;
                var failCount = 0;
                var errors = new List<string>();

                foreach (var bankId in request.BankIds)
                {
                    try
                    {
                        var bank = await _bankInfoService.GetBankInfoByIdAsync(bankId);
                        if (bank == null)
                        {
                            failCount++;
                            errors.Add($"银行ID {bankId} 不存在");
                            continue;
                        }

                        var updateRequest = new BankInfoUpdateRequest
                        {
                            StandardName = bank.StandardName,
                            ShortName = bank.ShortName,
                            EnglishName = bank.EnglishName,
                            BankCode = bank.BankCode,
                            IsActive = request.IsActive,
                            CardLengthRule = bank.CardLengthRule,
                            SupportedCardTypes = bank.SupportedCardTypes,
                            Remark = bank.Remark
                        };

                        var result = await _bankInfoService.UpdateBankInfoAsync(bankId, updateRequest, updatedBy);
                        if (result.success)
                        {
                            successCount++;
                        }
                        else
                        {
                            failCount++;
                            errors.Add($"银行ID {bankId}: {result.message}");
                        }
                    }
                    catch (Exception ex)
                    {
                        failCount++;
                        errors.Add($"银行ID {bankId}: {ex.Message}");
                    }
                }

                var message = $"批量操作完成，成功: {successCount}，失败: {failCount}";
                if (errors.Any())
                {
                    message += $"\n错误详情：\n{string.Join("\n", errors.Take(5))}";
                    if (errors.Count > 5)
                    {
                        message += $"\n...还有 {errors.Count - 5} 个错误";
                    }
                }

                return Ok(new 
                { 
                    message, 
                    successCount, 
                    failCount,
                    errors = errors.Take(10).ToList()
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量更新银行状态失败");
                return StatusCode(500, new { message = "批量更新银行状态失败", error = ex.Message });
            }
        }

        #region 私有方法

        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <returns></returns>
        private string? GetCurrentUser()
        {
            // 这里可以根据实际的身份验证机制来获取当前用户
            // 例如从JWT Token、Session或其他方式获取
            return User?.Identity?.Name ?? "System";
        }

        #endregion
    }

    /// <summary>
    /// 批量状态更新请求
    /// </summary>
    public class BatchStatusUpdateRequest
    {
        /// <summary>
        /// 银行ID列表
        /// </summary>
        [Required]
        public List<int> BankIds { get; set; } = new();

        /// <summary>
        /// 是否启用
        /// </summary>
        [Required]
        public bool IsActive { get; set; }
    }
}